#import <regex.h>
#import <sys/types.h>
#import <pwd.h>
#import <sys/dir.h> 
#import "StringStorage.h"
#import "Directory.h"

@implementation Directory

- init
{
   [super init];
   path = [[StringStorage alloc] init];
   return self;
}

- init: (const char *)aPath
{
   [self init];
   [self setPath: aPath];
   return self;
}

- free
{
   [path free];
   [self freeObjects];
   return [super free];
}

- setPath: (const char *)str
{
   char user[9];
   char fullPath[MAXPATHLEN + 1];
   DIR *dir;
   struct direct *entry;

   [path empty];
   [self freeObjects];

   if(str && *str == '~')		     /* used ~user or ~/ */
   {
      struct passwd *pw;
      int x;

      for(x = 1; str[x] && x < 9; x++)
	  if(str[x] == '/')
	      break;
	  else
	      user[x - 1] = str[x];
      
      user[x - 1] = (char)0;
      if(!strlen(user))			     /* was ~/ */
	  strcpy(user, NXUserName());

      pw = getpwnam(user);
      if(pw)
      {
	 strcpy(fullPath,pw->pw_dir);
	 strcat(fullPath,str + x);
	 str = fullPath;
      }
   }
   
   dir = opendir(str);			     /* open the resulting directory */

   if(!dir)				     /* failed to open */
       return nil;

   [path setStringValue: str];
   while(entry = readdir(dir))
       [self addObject: [[StringStorage alloc] init: entry->d_name]];
   closedir(dir);
   return self;
}


- (const char *)path
{
   return [path stringValue];
}


@end
